/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       fixedjoint.cpp
 * Author:     karooolek
 * Created on: 2010-04-11
 *
 **********************************************************************************************************************/

#include "fixedjoint.h"

namespace mGameEngine
{
namespace Physics
{

FixedJoint::FixedJoint() : Joint()
{
}

FixedJoint::~FixedJoint()
{
    // all done in ~Joint
}

void FixedJoint::create(NxActor *actor1, NxActor *actor2) const
{
    // two actors required
    if(!actor1 || !actor2)
    {
        return;
    }

    // already created
    if(_created)
    {
        return;
    }

#if 1
    // create joint
    NxDistanceJointDesc desc;

    // assign first actor
    if(actor1->isDynamic())
    {
        desc.actor[0] = actor1;
        desc.localAnchor[0] = NxVec3(_anchor1.m[3]);
    }
    else
    {
        desc.actor[0] = NULL;
        desc.localAnchor[0] = actor1->getGlobalPose() * NxVec3(_anchor1.m[3]);
    }

    // assign second actor
    if(actor2->isDynamic())
    {
        desc.actor[1] = actor2;
        desc.localAnchor[1] = NxVec3(_anchor2.m[3]);
    }
    else
    {
        desc.actor[1] = NULL;
        desc.localAnchor[1] = actor2->getGlobalPose() * NxVec3(_anchor2.m[3]);
    }

    desc.flags |= NX_DJF_MAX_DISTANCE_ENABLED | NX_DJF_SPRING_ENABLED;
    desc.maxDistance = 0.0f;
    desc.spring.spring = 100.f;
    desc.spring.damper = 0.9f;

    _joint = actor1->getScene().createJoint(desc);

    // problems while creating joint
    if(!_joint)
    {
        return;
    }

    // joint is created
    _created = true;

#else
    // TODO keep anchors together
    /*
    Matrix4x4 p1, p2;
    actor1->getGlobalPose().getColumnMajor44(p1._m);
    actor2->getGlobalPose().getColumnMajor44(p2._m);
    
    NxMat34 p;
    if(actor1->isDynamic())
    {
        p1 = p2 * _anchor2 * Matrix4x4(_anchor1).invert();
        p.setColumnMajor44(p1._m);
        actor1->setGlobalPose(p);
    }
    else if(actor2->isDynamic())
    {
        p2 = p1 * _anchor1 * Matrix4x4(_anchor2).invert();
        p.setColumnMajor44(p2._m);
        actor2->setGlobalPose(p);
    }
    */

    // create joint
    NxFixedJointDesc desc;
    desc.actor[0] = actor1->isDynamic() ? actor1 : NULL;
    desc.actor[1] = actor2->isDynamic() ? actor2 : NULL;
    desc.isValid();
    assert(_joint = actor1->getScene().createJoint(desc));

    // problems while creating joint
    if(!_joint)
    {
        return;
    }

    // joint is created
    _created = true;
#endif

}

}
}

